package com.hkyl.hospital.service.impl;

import com.hkyl.hospital.entity.Permission;
import com.hkyl.hospital.entity.PermissionExample;
import com.hkyl.hospital.entity.Role;
import com.hkyl.hospital.mapper.PermissionMapper;
import com.hkyl.hospital.mapper.custom.CustomRoleMapper;
import com.hkyl.hospital.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author whd
 * @date 2023/07/08 17:25:04
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private CustomRoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public List<Role> findAll() {
        return roleMapper.selectByExample(null);
    }

    @Override
    public int save(Role role) {
        return roleMapper.insertSelective(role);
    }

    @Override
    public int update(Role role) {
        return roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public int delete(Integer roleId) {
        clearPermissions(roleId);
        return roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public Role findOne(Integer roleId) {

        return roleMapper.selectOneWithPermissions(roleId);
    }

    @Override
    public List<Role> findRoleIdsByUserId(Integer userId) {
        List<Integer> roleIds = roleMapper.findRoleIdsByUserId(userId);
        List<Role> roles=new ArrayList<>();
        for (Integer roleId : roleIds) {
            Role role = roleMapper.selectByPrimaryKey(roleId);
            roles.add(role);
        }
        return roles;
    }


    private  int clearPermissions(Integer roleId){
        PermissionExample permissionExample = new PermissionExample();

        //查询用户对应权限的id
        List<Permission> permissions = findOne(roleId).getPermissions();
        if (permissions.size()==0) {
            return 0;
        }
        List<Integer> clearPermissionIds = permissions.stream().map(permission -> permission.getPermissionId()).collect(Collectors.toList());

        permissionExample.or().andPermissionIdIn(clearPermissionIds);
        //先删除对应id的权限
        return permissionMapper.deleteByExample(permissionExample);
    }

}
